from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response

from api.serializers.address_serializer import MailingAddressSerializer
from app.models.address import MailingAddress


@api_view(['GET'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def get_user_address(request: Request):
    user = request.user
    address_list = MailingAddress.objects.filter(user=user)
    serializer = MailingAddressSerializer(list(address_list), many=True)
    return Response(serializer.data)


@api_view(['POST'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def add_user_address(request: Request):
    serializer = MailingAddressSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(user=request.user)
        return Response(data={"detail": u"添加成功"})
    else:
        raise ValidationError(serializer.errors)


@api_view(['DELETE'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def delete_user_address(request: Request, address_id):
    try:
        MailingAddress.objects.get(pk=address_id, user=request.user).delete()
    except MailingAddress.DoesNotExist:
        raise NotFound(detail=u'用户地址不存在')

    return Response({'detail': u'删除成功'})


@api_view(['PUT'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def update_user_address(request: Request, address_id):
    print(request.data)
    data = dict(id=address_id, user=request.user.id)
    data.update(request.data)
    serializer = MailingAddressSerializer(data=data)
    if serializer.is_valid():
        try:
            address = MailingAddress.objects.get(id=address_id, user=request.user)
        except MailingAddress.DoesNotExist:
            raise NotFound(detail=u'用户地址不存在')
        serializer.update(validated_data=request.data, instance=address)
    else:
        raise ValidationError(serializer.errors)

    return Response({'detail': u'更新成功'})


@api_view(['POST'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def set_default_user_address(request: Request, address_id):
    try:
        address = MailingAddress.objects.get(user=request.user, id=address_id)
    except MailingAddress.DoesNotExist:
        raise NotFound()

    try:
        default_address = MailingAddress.objects.get(is_default=True, user=request.user)
        default_address.is_default = False
        default_address.save()
    except MailingAddress.DoesNotExist:
        pass
    address.is_default = True
    address.save()
    return Response(dict(detail=u'设置成功'))
